package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.*;
import com.leoman.entity.*;
import com.leoman.service.PlacardService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.QiNiuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * PlacardServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:00.
 */
@Service
public class PlacardServiceImpl implements PlacardService {

    @Autowired
    private PlacardDao placardDao;

    @Autowired
    private PraiseDao praiseDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private ImageDao imageDao;

    @Override
    public List<Placard> findAll() {
        return placardDao.findAll();
    }

    @Override
    public Page<Placard> find(int pageNum, int pageSize) {
        return placardDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Placard> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Placard getById(int id) {
        return placardDao.findOne(id);
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        List<String> tempUrl = new ArrayList<>();
        List<Image> imageList;
        Placard placard = placardDao.findOne(id);

        // 删除该公告的所有评论
        List<Comment> commentList = commentDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_PLACARD);
        for (Comment comment : commentList) {
            // 删除评论中的图片
            imageList = imageDao.findListByParams(comment.getId(), Constant.SOURCE_TYPE_COMMENT);
            System.out.println();
            for (Image image : imageList) {
                tempUrl.add(image.getUrl());
                imageDao.delete(image);
            }
            System.out.println();
            // 删除评论中的语音文件
            if (comment.getVoiceTime() > 0) {
                tempUrl.add(comment.getContent());
            }

            commentDao.delete(comment.getId());
        }

        // 删除该公告的所有收藏
        List<UserCollect> collectList = userCollectDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_PLACARD);
        for (UserCollect userCollect : collectList) {
            userCollectDao.delete(userCollect);
        }

        // 删除该公告的所有点赞
        List<Praise> praiseList = praiseDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_PLACARD);
        for (Praise praise : praiseList) {
            praiseDao.delete(praise);
        }

        tempUrl.add(placard.getCover());

        placardDao.delete(id);

        for (String url : tempUrl) {
            QiNiuUtils.delete(url);
        }
    }

    @Override
    public Placard create(Placard placard) {
        return placardDao.save(placard);
    }

    @Override
    public Placard update(Placard placard) {
        return placardDao.save(placard);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<Placard> iPageForApp(final Integer userId, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);

        Page<Placard> page = placardDao.findAll(new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "isTop", "id"));

        for (Placard placard : page.getContent()) {
            changePlacardInfo(placard, userId);
        }

        return page;
    }

    @Override
    public Page<Placard> pageByParams(final String userName, final String startTime, final String endTime, Integer pageNum, Integer pageSize) {
        return placardDao.findAll(new Specification<Placard>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Placard> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (StringUtils.isNotBlank(userName)) {
                    predicateList.add(cb.like(root.get("admin").get("nickname").as(String.class), "%" + userName + "%"));
                }

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        System.out.println("_-_");
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        System.out.println("_-_");
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "isTop", "id"));
    }

    @Override
    public Integer toTop(Integer placardId) {
        try {
            Placard topMind = placardDao.iFindOneWithTop();
            Placard mind = placardDao.findOne(placardId);

            if (null != topMind && placardId.equals(topMind.getId())) {
                return -1;
            }

            if (null != topMind) {
                topMind.setIsTop(Constant.USER_STATUS_NO);
                placardDao.save(topMind);
            }

            mind.setIsTop(Constant.USER_STATUS_YES);
            placardDao.save(mind);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchDelete(String ids) {
        try {
            Integer[] mindIds = JsonUtil.json2Obj(ids, Integer[].class);
            System.out.println("");
            for (Integer mindId : mindIds) {
                deleteById(mindId);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer savePlacard(Admin admin, String title, String txtVal, String content, MultipartRequest multipartRequest) {
        try {
            MultipartFile cover = multipartRequest.getFile("cover");

            Placard placard = new Placard();
            placard.setAdmin(admin);
            placard.setTitle(title);
            if (txtVal.length() > 40) {
                placard.setSynopsis(txtVal.substring(0, 40));
            } else {
                placard.setSynopsis(txtVal);
            }
            placard.setContent(content);
            if (null != cover && cover.getSize() > 0) {
                placard.setCover(QiNiuUtils.upload(cover));
            }

            placardDao.save(placard);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 加载黑板公告附属信息
     *
     * @param placard 黑板公告信息
     * @param userId  用户ID
     */
    private void changePlacardInfo(Placard placard, Integer userId) {
        if (null == userId) {
            placard.setIsPraise(Constant.USER_STATUS_NO);
        } else {
            placard.setIsPraise(null == praiseDao.findOneByParams(userId, placard.getId(), Constant.SOURCE_TYPE_PLACARD) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
        }

        Integer praiseNum = praiseDao.findListBySourceIdAndType(placard.getId(), Constant.SOURCE_TYPE_PLACARD).size();
        Integer commentNum = commentDao.findListBySourceIdAndType(placard.getId(), Constant.SOURCE_TYPE_PLACARD).size();

        placard.setPraiseNum(praiseNum * 2 + commentNum);
        placard.setCommentNum(commentNum);
        placard.setContent(placard.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));
    }
}